package com.ruoyi.system.controller;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import com.deepoove.poi.data.MiniTableRenderData;
import com.deepoove.poi.data.PictureRenderData;
import com.deepoove.poi.data.RowRenderData;
import com.deepoove.poi.data.TextRenderData;
import com.deepoove.poi.policy.HackLoopTableRenderPolicy;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.system.domain.SpBmlist;
import com.ruoyi.system.domain.SpSaicheng;
import com.ruoyi.system.service.ISpBmlistService;
import com.ruoyi.system.service.ISpSaichengService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SpDaibiao;
import com.ruoyi.system.service.ISpDaibiaoService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 代队Controller
 * 
 * @author ruoyi
 * @date 2022-11-11
 */
@RestController
@RequestMapping("/system/daibiao")
public class SpDaibiaoController extends BaseController
{
    @Autowired
    private ISpDaibiaoService spDaibiaoService;
    @Autowired
    private ISpSaichengService spSaichengService;
    @Autowired
    private ISpBmlistService spBmlistService;

    /**
     * 查询代队列表
     */
    @PreAuthorize("@ss.hasPermi('system:daibiao:list')")
    @GetMapping("/list")
    public TableDataInfo list(SpDaibiao spDaibiao)
    {
        startPage();
        List<SpDaibiao> list = spDaibiaoService.selectSpDaibiaoList(spDaibiao);
        return getDataTable(list);
    }

    /**
     * 导出代队列表
     */
    @PreAuthorize("@ss.hasPermi('system:daibiao:export')")
    @Log(title = "代队", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SpDaibiao spDaibiao)
    {
        List<SpDaibiao> list = spDaibiaoService.selectSpDaibiaoList(spDaibiao);
        ExcelUtil<SpDaibiao> util = new ExcelUtil<SpDaibiao>(SpDaibiao.class);
        util.exportExcel(response, list, "代队数据");
    }


    @PostMapping("/export3")
    public void export3(HttpServletResponse response, SpDaibiao spDaibiao)
    {
        List<SpDaibiao> list = spDaibiaoService.selectSpDaibiaoList(spDaibiao);
        ExcelUtil<SpDaibiao> util = new ExcelUtil<SpDaibiao>(SpDaibiao.class);
        util.exportExcel(response, list, "代队数据");
    }

    @PostMapping("/exportword")
    public void exportword(HttpServletResponse response, SpDaibiao spDaibiao) {
        String basefilePath = RuoYiConfig.getUploadPath();
        List<SpDaibiao> list = spDaibiaoService.selectSpDaibiaoListWeb(spDaibiao);
        SpSaicheng sc = spSaichengService.selectSpSaichengByScId(spDaibiao.getScId());
        File folder = new File(basefilePath + "/" + sc.getScId() + "/");
        if (!folder.exists()) {
            folder.mkdir();
        }
        File[] files = folder.listFiles();
        // 遍历并删除所有文件
        for (File file : files) {
            if (file.isFile()) {
                file.delete();
            }
        }
        for (SpDaibiao daibiao : list) {
            Map<String, Object> map = new HashMap<>();



            map.put("orgName", daibiao.getGname());
            map.put("scName", sc.getTitle());
            map.put("jieshao", daibiao.getJieshao());
            map.put("userName", daibiao.getUsername());
            map.put("userdn", daibiao.getUserdn());
            map.put("jlname", daibiao.getJlname());
            map.put("jldn", daibiao.getJldn());

            String filePath = basefilePath + daibiao.getgPic().replace("/profile/upload","");
            map.put("image", new PictureRenderData(540, 360, filePath));


            RowRenderData header = RowRenderData.build(
                    new TextRenderData("FFFFFF", "姓名"),
                    new TextRenderData("FFFFFF", "性别"),
                    new TextRenderData("FFFFFF", "身份证"),
                    new TextRenderData("FFFFFF", "全国统一学籍号")
            );

            SpBmlist query = new SpBmlist();
            query.setDbId(daibiao.getDbId());
            List<SpBmlist> bmlist = spBmlistService.selectSpBmlistList(query);
            List<RowRenderData> list2 = new ArrayList<RowRenderData>();
            int inedex = 0;
            for (SpBmlist bp : bmlist) {
                inedex = inedex + 1;
                RowRenderData row = RowRenderData.build(
                        new TextRenderData("FFFFFF", bp.getSpName()),
                        new TextRenderData("FFFFFF", bp.getSex()),
                        new TextRenderData("FFFFFF", bp.getIdno()),
                        new TextRenderData("FFFFFF", bp.getUserCode())
                );
                list2.add(row);
            }


            map.put("table", new MiniTableRenderData(header, list2));
            ConfigureBuilder builder = Configure.newBuilder();
            HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();
            builder.bind("bianpaiList", policy);
            map.put("bianpaiList", bmlist);

            Configure configure = builder.build();
            XWPFTemplate template = XWPFTemplate.compile(basefilePath + "/tempword.docx", configure).render(map);
            try {
                if(daibiao.getWordFile()!=null){
                    File picfile = new File(basefilePath + "/"+daibiao.getWordFile().replace("/profile/upload",""));
                    File destFile = new File(basefilePath + "/" + sc.getScId() + "/" +daibiao.getGname()+"签章图片."+ FilenameUtils.getExtension(picfile.getName()));
                    FileInputStream inputStream = new FileInputStream(picfile);
                    FileOutputStream outputStream = new FileOutputStream(destFile);





                    // 读取源文件并写入目标文件
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = inputStream.read(buffer)) > 0) {
                        outputStream.write(buffer, 0, length);
                    }

                    // 关闭输入流和输出流
                    inputStream.close();
                    outputStream.close();

                }



                FileOutputStream out = new FileOutputStream(basefilePath + "/" + sc.getScId() + "/" + daibiao.getGname() + "报名表.docx");
                template.write(out);
                out.flush();
                out.close();
                template.close();
            } catch (IOException e) {
                e.printStackTrace();
            }


        }


        String fileName = "打包报名表.zip";
        response.setContentType("application/zip");
        response.setHeader("content-disposition", "attachment;filename=" + fileName);

        ZipOutputStream zos = null;
        BufferedInputStream bis = null;
        try{
            zos = new ZipOutputStream(response.getOutputStream());
            byte[] buf = new byte[8192];
            int len;
            File[] files2 = folder.listFiles();
            for(File file:files2){
                if (!file.isFile()) {
                    continue;
                }
                ZipEntry ze = new ZipEntry(file.getName());
                zos.putNextEntry(ze);
                bis = new BufferedInputStream(new FileInputStream(file));
                while ((len = bis.read(buf)) > 0) {
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
            }

            zos.closeEntry();
        }catch(Exception ex){
            ex.printStackTrace();
        }finally {
            if(bis != null){
                try{
                    bis.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
            if(zos != null){
                try{
                    zos.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }



    }



    @PostMapping ("/zip")
    public void downloadZip(HttpServletResponse response, SpDaibiao spDaibiao){
        LoginUser loginUser = SecurityUtils.getLoginUser();

        String basefilePath = RuoYiConfig.getUploadPath();

        String fileName = "files.zip";
        response.setContentType("application/zip");
        response.setHeader("content-disposition", "attachment;filename=" + fileName);

        ZipOutputStream zos = null;
        BufferedInputStream bis = null;
        try{
            zos = new ZipOutputStream(response.getOutputStream());
            byte[] buf = new byte[8192];
            int len;
            File folder = new File(basefilePath + "/" + spDaibiao.getScId() + "/");
            File[] files2 = folder.listFiles();
            for(File file:files2){
                if (!file.isFile()) {
                    continue;
                }
                ZipEntry ze = new ZipEntry(file.getName());
                zos.putNextEntry(ze);
                bis = new BufferedInputStream(new FileInputStream(file));
                while ((len = bis.read(buf)) > 0) {
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
            }
            zos.closeEntry();
        }catch(Exception ex){
            ex.printStackTrace();
        }finally {
            if(bis != null){
                try{
                    bis.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
            if(zos != null){
                try{
                    zos.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 获取代队详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:daibiao:query')")
    @GetMapping(value = "/{dbId}")
    public AjaxResult getInfo(@PathVariable("dbId") Long dbId)
    {
        return AjaxResult.success(spDaibiaoService.selectSpDaibiaoByDbId(dbId));
    }

    /**
     * 新增代队
     */
    @PreAuthorize("@ss.hasPermi('system:daibiao:add')")
    @Log(title = "代队", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SpDaibiao spDaibiao)
    {
        return toAjax(spDaibiaoService.insertSpDaibiao(spDaibiao));
    }

    /**
     * 修改代队
     */
    @PreAuthorize("@ss.hasPermi('system:daibiao:edit')")
    @Log(title = "代队", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SpDaibiao spDaibiao)
    {
        return toAjax(spDaibiaoService.updateSpDaibiao(spDaibiao));
    }

    /**
     * 删除代队
     */
    @PreAuthorize("@ss.hasPermi('system:daibiao:remove')")
    @Log(title = "代队", businessType = BusinessType.DELETE)
	@DeleteMapping("/{dbIds}")
    public AjaxResult remove(@PathVariable Long[] dbIds)
    {
        return toAjax(spDaibiaoService.deleteSpDaibiaoByDbIds(dbIds));
    }
}
